package com.heima;

import java.util.Calendar;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2022/1/28 12:11
 *
 *  main方法中创建delayQueue队列并向延迟队列中添加三个延迟任务
 *
 *
 */
public class DelayedTask implements Delayed {

    private int executeTime = 0;

    public DelayedTask(int delay){
        Calendar calendar =  Calendar.getInstance();
        calendar.add(Calendar.SECOND, delay);
        this.executeTime = (int)(calendar.getTimeInMillis() / 1000);
    }

    /**
     * 元素在队列中的剩余时间
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        Calendar calendar = Calendar.getInstance();
        return executeTime - (calendar.getTimeInMillis() / 1000);
    }

    /**
     * 元素排列
     * @param o
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        long var = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return var == 0 ? 0 : (var < 0 ? -1 : 1);
    }


    public static void main(String[] args) {
        DelayQueue<DelayedTask> queue = new DelayQueue<>();
        queue.add(new DelayedTask(5));
        queue.add(new DelayedTask(10));
        queue.add(new DelayedTask(15));

        System.out.println(System.currentTimeMillis() / 1000 + "start consume");
        while(queue.size() != 0){
            DelayedTask delayedTask = queue.poll();
            if (delayedTask != null){
                System.out.println();
            }

        }

    }
}
